import ErrorComp from '@/components/common/error-comp';
import DownToTopView from '@/components/common/motion/down-to-top-view';
import QueryImage from '@/components/common/query-image';
import OrderSearch from '@/components/user/order-search';
import Pagination from '@/components/user/pagination';
import { orderStatusValues } from '@/lib/db/schema/enum';
import { listUserOrdersByPage } from '@/service/query/order';
import {
  getJsonToEnumArraySchema,
  jsonToDateRangeSchema,
  pageSchema,
} from '@/service/query/schema/common';
import { userOrderSearchSchema } from '@/service/query/schema/order';
import type { SearchParams } from '@/service/type/common';
import { orderStatusMap } from '@/service/type/order';
import dayjs from 'dayjs';
import Link from 'next/link';

export const metadata = {
  title: '订单管理',
};

const PageSchema = pageSchema
  .merge(userOrderSearchSchema)
  .omit({
    status: true,
    dateRange: true,
  })
  .extend({
    status: getJsonToEnumArraySchema(orderStatusValues),
    dateRange: jsonToDateRangeSchema,
  });

export default async function Page({
  searchParams,
}: { searchParams: SearchParams }) {
  const params = PageSchema.safeParse(await searchParams);
  if (!params.success) return <ErrorComp message="参数错误" />;

  const { result, error } = await listUserOrdersByPage({
    page: params.data.page,
    pageSize: params.data.pageSize,
    shopName: params.data.shopName,
    status: params.data.status,
    dateRange: params.data.dateRange,
  });
  if (error) return <ErrorComp message={error.message} />;

  return (
    <div className=" pb-10 space-y-5 px-16 pt-20 min-h-screen shadow-lg">
      <div className="flex justify-end px-5">
        <OrderSearch />
      </div>
      <DownToTopView>
        <div className="space-y-2">
          {result.data.map((order) => (
            <div key={order.id} className="hover:bg-muted rounded-lg p-5">
              <div className="space-y-3">
                <div className="flex justify-between">
                  <Link href={`/detail-shop/${order.shop.id}`}>
                    <div className="font-bold group flex items-center">
                      {order.shop.name}
                      <span className="i-ri-arrow-right-s-line opacity-0 group-hover:opacity-100 group-hover:translate-x-1 transition-all" />
                    </div>
                  </Link>
                  <div className="text-sm">
                    订单状态：
                    {orderStatusMap[order.status]}
                  </div>
                </div>
                <div className="flex justify-between items-end">
                  <div className="flex gap-3">
                    {order.products.slice(0, 5).map((p) => {
                      const product = order.shop.products.find(
                        (sp) => sp.id === p.id,
                      );
                      if (!product || product.imageKeys.length === 0)
                        return null;
                      return (
                        <QueryImage
                          key={product.id}
                          imageKey={product.imageKeys[0]}
                          wrapperClassName="w-20 h-12 shrink-0 rounded-lg"
                          imgClassName="w-full h-full object-cover"
                        />
                      );
                    })}
                  </div>
                  <div className="flex flex-col items-end gap-2">
                    <Link
                      href={`/order/${order.id}`}
                      className="text-sm hover:underline flex items-center group"
                    >
                      订单详情
                      <span className="i-ri-arrow-right-s-line group-hover:translate-x-1 transition-transform" />
                    </Link>
                    <div className="text-muted-foreground text-xs">
                      {dayjs(order.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </DownToTopView>
      <Pagination next={result.next} />
    </div>
  );
}
